import pyautogui
import keyboard
import time
import os
import json

from input_type_demo import switch_to_english, smart_type

USERNAME = "pythonBlue1"
PASSWORD = "KIYI1217"
CONFIG_FILE = "game_config.json"  # 配置文件路径


def load_config():
    """加载已有配置"""
    if os.path.exists(CONFIG_FILE):
        with open(CONFIG_FILE, 'r') as f:
            return json.load(f)
    return None


def save_config(positions):
    """保存配置到文件"""
    with open(CONFIG_FILE, 'w') as f:
        json.dump(positions, f)
    print("配置已保存！")


def setup_login_elements():
    """首次使用时设置登录元素位置"""
    print("\n=== 首次使用配置 ===")
    print("请按提示定位游戏登录界面元素：")

    elements = {
        "username_pos": "用户名输入框",
        "password_pos": "密码输入框",
        "login_button_pos": "登录按钮"
    }

    positions = {}
    for key, desc in elements.items():
        input(f"请将鼠标移动到【{desc}】上，然后按回车...")
        positions[key] = {
            "x": pyautogui.position().x,
            "y": pyautogui.position().y
        }
        print(f"已记录：{desc}位置 ({positions[key]['x']}, {positions[key]['y']})")

    save_config(positions)
    return positions


def smart_launch():
    """智能启动方案，尝试多种方式"""
    methods = [
        try_activate_window,
        try_shortcut,
        try_simulate_manual
    ]

    for method in methods:
        if method():
            return True
    return False


def try_activate_window():
    """方式1：激活已有窗口"""
    try:
        win = pyautogui.getWindowsWithTitle("奶块")[0]
        win.activate()
        # win.maximize()
        print("√ 通过窗口激活成功")
        return True
    except:
        return False


def try_shortcut():
    """方式2：快捷方式启动"""
    try:
        desktop = os.path.join(os.path.expanduser('~'), 'Desktop')
        os.startfile(os.path.join(desktop, "奶块.lnk"))
        print("√ 通过快捷方式启动成功")
        time.sleep(10)
        return True
    except:
        return False

def try_simulate_manual():
    """方式3：模拟手动操作"""
    try:
        pyautogui.hotkey('win')
        time.sleep(1)
        pyautogui.write("奶块")
        time.sleep(2)
        pyautogui.press('enter')
        print("√ 模拟手动启动成功")
        time.sleep(10)
        return True
    except:
        return False

def login():
    """使用已有配置自动登录"""
    config = load_config()

    if not config:
        config = setup_login_elements()

    print("\n=== 正在自动登录 ===")
    switch_to_english()
    # 输入用户名
    pyautogui.click(config["username_pos"]["x"], config["username_pos"]["y"],
                   clicks=2, interval=0.15)
    # smart_type(USERNAME)
    pyautogui.write(USERNAME, interval=0.1)
    # 输入密码
    pyautogui.click(config["password_pos"]["x"], config["password_pos"]["y"],
                   clicks=2, interval=0.15)
    # smart_type(PASSWORD)
    pyautogui.write(PASSWORD, interval=0.1)
    # 点击登录
    pyautogui.click(config["login_button_pos"]["x"], config["login_button_pos"]["y"])
    print("登录流程完成！")


def login_to_game():
    print("=== 奶块智能登录脚本 ===")
    print("尝试自动启动游戏...")

    # if not smart_launch():
    #     print("自动启动失败，请手动启动游戏")
    #     input("手动启动完成后按回车继续...")
    time.sleep(5)

    login()
    print("5秒后自动退出...")
    time.sleep(5)


if __name__ == "__main__":
    pyautogui.PAUSE = 0.5
    login_to_game()